package com.sky.task;


import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务类(这个也需要我们交给IOC容器管理)
 */
@Component
@Slf4j
public class MyOrderTask {
    @Autowired
    private OrderMapper orderMapper;
    //下面两个定时任务也是基础的crud

    /**
     * 定时处理超时
     */
    @Scheduled(cron ="0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单:{}", LocalDateTime.now());
        //这里就使用我们的对应api
        List<Orders> selectfortimeout = orderMapper.selectfortimeout(Orders.UN_PAID, LocalDateTime.now().plusMinutes(-15));
        //处于代付款状态 并且时间超过了十五分钟  如果超时就取消订单
        if(selectfortimeout.size()>0&& selectfortimeout!=null){
            //这里就更新我们的状态
            for(Orders order:selectfortimeout){
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时 自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理派送中异常
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processUnfinishedOrder(){
        //查->改
        List<Orders> selectfortimeout = orderMapper.selectfortimeout(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if(selectfortimeout.size()>0&& selectfortimeout!=null){
            for(Orders order:selectfortimeout){
                order.setStatus(Orders.COMPLETED);
                orderMapper.updateonlystatus(order);
            }
        }
    }
}
